package com.uvnos4j.matilda.commons.utils;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 用户工具类
 * <p>
 * Description:用户工具类
 * </p>
 *
 * @author Guo.wl
 * @version v1.0.0
 * @see com.uvnos4j.matilda.commons.utils
 * @since 2020-08-31 23:31:52
 */
public class UserUtil {
    /**
     * 获取当前经过认证的省份信息
     *
     * @return 用户的名称
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }


    /**
     * 获取当前经过身份验证的用户的名称
     *
     * @return 用户的名称
     */
    public static String getUsername() {
        try {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (principal instanceof UserDetails) {
                return ((UserDetails) principal).getUsername();
            }
            return principal.toString();
        } catch (Throwable e) {
            // 不加载安全框架时，获取用户名逻辑
            return "dev";
        }
    }

}